package com.yc.navy.goods.controller;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yc.navy.goods.dto.AdminInfoDTO;
import com.yc.navy.goods.dto.AdminInfoDTODTO;
import com.yc.navy.goods.enums.ResultEnum;
import com.yc.navy.goods.service.IAdminInfoService;
import com.yc.navy.goods.util.ConstantInfo;
import com.yc.navy.goods.util.StringUtil;
import com.yc.navy.goods.vo.ResultVO;
import com.yc.navy.goods.vo.StreamVO;
import com.yc.navy.goods.websocket.WebServerSocket;


@Controller
@RequestMapping("/admin")
public class AdminInfoController {
	@Autowired
	private IAdminInfoService adminInfoService;
	
	/**
	 * 登录
	 * @param session
	 * @param af
	 * @return
	 */
	@PostMapping("/login")
	@ResponseBody
	public ResultVO login(HttpSession session, AdminInfoDTO af) {
		AdminInfoDTO admin = adminInfoService.login(af);
		if(admin == null) {
			return new ResultVO(ResultEnum.NOTLOGIN);
		}
		WebServerSocket wss = WebServerSocket.getWebServerSocket(String.valueOf(admin.getAno()));
		if(wss != null) {
			wss.sendMessage("101");
		}
		AdminInfoDTODTO adminDTO = new AdminInfoDTODTO();
		BeanUtils.copyProperties(admin, adminDTO);
		
		session.setAttribute(ConstantInfo.CURRENTLOGINADMIN, adminDTO);
		int result = adminInfoService.addNumber(admin.getAno());
		if(result == -1) {
			return new ResultVO(ResultEnum.ERROR);
		}
		return new ResultVO(ResultEnum.SUCCESS);
	}
	
	@GetMapping("/loginout")
	public String loginout(HttpSession session) {
		session.removeAttribute(ConstantInfo.CURRENTLOGINADMIN);
		return "redirect:/back/login.html";
	}
	/**
	 * 检查是否登录
	 * @param session
	 * @return
	 */
	@GetMapping("/check")
	@ResponseBody
	public ResultVO checkLogin(HttpSession session) {
		Object obj = session.getAttribute(ConstantInfo.CURRENTLOGINADMIN);
		if(obj == null) {
			return new ResultVO(ResultEnum.NOTLOGIN);
		}
		return new ResultVO(ResultEnum.SUCCESS, obj);
	}
	
	/**
	 * 查询所有管理员
	 * @param session
	 * @return
	 */
	@GetMapping("/list")
	@ResponseBody
	public StreamVO list(HttpSession session, @RequestParam("page") int page,@RequestParam("limit") int limit) {
		Object obj = session.getAttribute(ConstantInfo.CURRENTLOGINADMIN);
		if(obj == null) {
			return new StreamVO(ResultEnum.NOTLOGIN);
		}
		Map<String,Object> map = new HashMap<String,Object>();
		if(!StringUtil.checkNull(page,limit)){
			map.put("page", page);
			map.put("limit",limit);
		}
		return adminInfoService.findByPageForBack(map);

	}
	

}
